package com.tduck.cloud.api.web.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tduck.cloud.account.entity.UserEntity;
import com.tduck.cloud.account.service.UserService;
import com.tduck.cloud.api.util.UipUtils;
import com.tduck.cloud.common.constant.UipConstant;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

/**
 * 从友空间同步员工岗位信息
 *
 * @author Guard Baby
 * @date 2023/09/07
 */

@Slf4j
public class PostAsyncJob implements Job {
    @Resource
    private UserService userService;
    @Resource
    private UipUtils uipUtils;

    @Resource
    private ThreadPoolTaskExecutor taskExecutor;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        log.info("^^^^^^^^^^^友空间岗位同步任务开始^^^^^^^^^^");
        List<Long> userIds = userService.query().select("id").eq("dr", 0).isNotNull("code").list().stream().map(UserEntity::getId).collect(Collectors.toList());
        if (CollUtil.isEmpty(userIds)) {
            log.error("userIds为空");
        }
        log.info("共获取到{}个id", userIds.size());
        CountDownLatch countDownLatch = new CountDownLatch(userIds.size());
        for (Long userId : userIds) {
            Runnable runnable = () -> {
                countDownLatch.countDown();
                String result = uipUtils.queryHRCStaffDetail(userId);
                JSONObject resultJson = JSONObject.parseObject(result);
                String code = resultJson.getString("code");
                if (!UipConstant.SUCCESS_CODE.equals(code)) {
                    log.error("获取员工详情失败，userId:{},result:{}", userId, result);
                    return;
                }
                JSONObject data = resultJson.getJSONObject("data");
                JSONArray staffJobs = data.getJSONArray("staffJob");
                if (CollUtil.isEmpty(staffJobs)) {
                    log.error("任职信息为空");
                    return;
                }
                String name = data.getString("name");
                for (int i = 0; i < staffJobs.size(); i++) {
                    JSONObject staffJob = staffJobs.getJSONObject(i);
                    Boolean isMainJob = staffJob.getBoolean("isMainJob");
//                    Boolean lastFlag = staff.getBoolean("lastFlag");
                    Long postId = staffJob.getLong("postId");
                    if (isMainJob) {
                        String postName = staffJob.getString("postName");
                        if (StrUtil.isBlank(postName)) {
                            String postResult = uipUtils.queryPosition(postId);
                            JSONObject postResultJson = JSON.parseObject(postResult);
                            if (UipConstant.SUCCESS_CODE.equals(postResultJson.getString("code"))) {
                                postName = postResultJson.getJSONObject("data").getJSONObject("name").getString("zh_CN");
                            }
                        }
                        log.info("name:{},id:{},postId:{},postName:{}", name, userId, postId, postName);
                        if (Objects.nonNull(postId) && StrUtil.isNotBlank(postName)) {
                            userService.update().eq("id", userId).set("post_id", postId).set("post_name", postName).update();
                            break;
                        }
                    }
                }
            };
            taskExecutor.execute(runnable);
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            log.error("countDownLatch error", e);
        }
        log.info("^^^^^^^^^^^友空间岗位同步任务结束^^^^^^^^^^");
    }


}
